import L from 'leaflet';
import styles from './index.less';
import { lmd } from './mock/lmd';
var polyline_group;//卡车路线
var polyline_groupAll;//全部卡车路线
var polyline_startmarker;//卡车起始
var polyline_startmarkerAll = [];//全部卡车起始
var polyline_startmarkerAllUpdate = '';//全部卡车  当前点击的车
var polyline_endmarker;//卡车终点
var polyline_endmarkerAll;//全部卡车状态下终点
var circleMarker_item = [];//单个卡车状态下显示的圆 （紫色）
var circleMarker_itemAll = [];// 单个卡车状态下可点击圆 （透明，扩大紫色点击区域）
var clonecircleMarker_item = [];//全部卡车状态下显示的圆 （紫色）
var clonecircleMarker_itemAll = [];// 全部卡车状态下可点击圆 （透明，扩大紫色点击区域）
var circle_GantryCrane;//单个龙门吊
var circle_GantryCraneAll = [];//全部龙门吊
var circle_TravellingBridge;//单个桥吊
var circle_TravellingBridgeAll = [];//全部桥吊
var popup_TraveAll = [];//桥吊弹窗
var popup_GantryAll = [];//龙门吊弹窗
var popup_ComAll = [];//集卡弹窗
var jk = [];
var timer1 = [];
var timer3 = [];
var popup_TraveAlls = [];
var jksp = true;
var lmdsp = true;
//绘制禁区
export async function drawForbiddenZone(This) {
  const { state } = This;
  const {
    nodeMap,              //节点地图
    forbiddenZones,       //禁区
  } = state.mapinfo;

  for (let i = 0; i < forbiddenZones.length; i++) {
    const { id, nds } = forbiddenZones[i];
    const latlngs = [];

    for (let iN = 0; iN < nds.length; iN++) {
      const { lat, lon } = nodeMap[nds[iN]];
      latlngs.push([lat, lon]);
    }

    //多边形
    L.polygon(latlngs, {
      color: '#FF6347',
      fillColor: '#FF6347',
      weight: 1,
    }).addTo(state.map);
  }
}

//红色无法驶入的区域
export async function drawRoadEdge(This) {
  const { state } = This;
  const {
    nodeMap,                //节点地图
    roadEdges,              //道路边缘
  } = state.mapinfo
  //绘制道路边缘(实线)
  for (let i = 0; i < roadEdges.length; i++) {
    const { id, nds } = roadEdges[i];
    const latlngs = [];

    for (let iN = 0; iN < nds.length; iN++) {
      const { lat, lon } = nodeMap[nds[iN]];
      latlngs.push([lat, lon]);
    }
    //多边形
    L.polygon(latlngs, {
      color: '#FF6347',
      fillColor: '#FF6347',
      weight: 1,
    }).addTo(state.map);
  }
}

//绘制扩展点
export async function drawExtraPoint(This) {
  const { state } = This;
  const {
    nodeMap, //节点地图
    extraPoints, //扩展点
  } = state.mapinfo;
  for (let i = 0; i < extraPoints.length; i++) {
    const { id, nds } = extraPoints[i];
    const latlngs = [];

    for (let iN = 0; iN < nds.length; iN++) {
      const { lat, lon } = nodeMap[nds[iN]];
      latlngs.push([lat, lon]);
    }
    // 道路交汇区
    //线
    //L.polyline(latlngs, {color: '#008000', weight:1}).addTo(state.map);
    //多边形
    L.polygon(latlngs, {
      color: '#008000',
      fillColor: '#008000',
      weight: 1,
    }).addTo(state.map);
  }
}

//绘制路段
export async function drawRoad(This, laneMarkerMap) {
  const { state } = This;
  const {
    nodeMap,                //节点地图
    forbiddenZones,         //禁区
    roadEdges,              //道路边缘
    extraPoints,            //扩展点
    laneMarkers,            //路标信息
    pavements,              //路面信息
    connections,            //连接信息
    sections,               //路段信息
  } = state.mapinfo;
  for (let i = 0; i < sections.length; i++) {
    const { id, lane } = sections[i];

    var latlngs = [];
    for (let iN = 0; iN < lane.length; iN++) {
      const { id, leftLanemarker, rightLanemarker } = lane[iN];

      const leftnds = laneMarkerMap[leftLanemarker].nds;
      for (let cl = 0; cl < leftnds.length; cl++) {
        const { lat, lon } = nodeMap[leftnds[cl]];
        latlngs.push([lat, lon]);
      }

      const rightnds = laneMarkerMap[rightLanemarker].nds;
      for (let cr = rightnds.length - 1; cr >= 0; cr--) {
        const { lat, lon } = nodeMap[rightnds[cr]];
        latlngs.push([lat, lon]);
      }
    }
    //多边形
    L.polygon(latlngs, {
      color: '#008000',
      fillColor: '#008000',
      weight: 1,
    }).addTo(state.map);
    //L.polyline(latlngs, {color: '#008000', weight:1}).addTo(state.map);
  }
}

//绘制路面
export async function drawPavement(This) {
  const { state } = This;
  const {
    nodeMap,            //节点地图
    pavements,          //路面信息
  } = state.mapinfo;
  for (let i = 0; i < pavements.length; i++) {
    const pavement = pavements[i];

    for (let n = 0; n < pavement.lines.length; n++) {
      const { id, nds } = pavement.lines[n];
      const latlngs = [];

      for (let iN = 0; iN < nds.length; iN++) {
        const { lat, lon } = nodeMap[nds[iN]];
        latlngs.push([lat, lon]);
      }
      //线
      L.polyline(latlngs, { color: '#1E90FF', weight: 1 }).addTo(state.map);
      //多边形
      //L.polygon(latlngs, {color: '#1E90FF',fillColor:'#1E90FF',weight:1}).addTo(state.map);
    }
  }
}

//绘制连接
export async function drawConnection(This) {
  const { state } = This;
  const {
    connections, //连接信息
  } = state.mapinfo;
  //绘制连接
  for (let i = 0; i < connections.length; i++) {
    const { center } = connections[i];
    const { lat, lon } = center;
    // 中心点
    L.circle([lat, lon], {
      color: '#00FF7F',
      fillColor: '#00FF7F',
      radius: 1,
      fillOpacity: 1,
      weight: 1,
    }).addTo(state.map);
  }
}


// 
export async function latLonLists(This) {
  const { state } = This;
  var latLonList = state.common.latLonList;
  var arr = [];
  for (var i in latLonList) {
    var arr7 = [];
    for (var j in latLonList[i]) {
      arr7.push(latLonList[i][j]);
    }
    arr.push(arr7);
  }
  const {
    nodeMap, //节点地图
    roadEdges, //道路边缘
  } = state.mapinfo;
  L.polyline(arr, {
    color: '#ea4335',
    fillColor: '#ea4335',
    weight: 10,
  }).addTo(state.map);
}

//绘制卡车路线
export async function drawgetTruck(This) {
  deleteAllPopup(This, jk)
  deleteAllPopup(This, popup_TraveAlls)
  // polyline.removeFrom(map)
  const { state } = This;
  const comData = state.comData;
  const latlngs = comData.firstLatLonList;
  if (popup_ComAll.length) {
    for (var item of popup_ComAll) {
      state.map.removeLayer(item)
    }
    popup_ComAll = []
  }
  // icon 图层
  var myIcon = L.icon({
    iconUrl: require('/src/assets/truck.png'),
    iconSize: [25, 25],
    iconAnchor: [10, 15],
    popupAnchor: [-3, -76],
  });
  var endIcon = L.divIcon({
    html: '终点',
    className: styles.myDivIcon,
    iconSize: 30
  })
  deleteTruck(state)
  if (latlngs === null || !latlngs) return;
  polyline_startmarker = L.marker(latlngs[0], { icon: myIcon, title: '卡车路线' }).addTo(state.map);
  polyline_group = L.polyline(latlngs, { color: 'blue', weight: 2 }).addTo(state.map);
  polyline_endmarker = L.marker(latlngs[latlngs.length - 1], { icon: endIcon, title: '卡车路线' }).addTo(state.map);
  for (var i = 0; i < latlngs.length; i++) {
    // 路线圆圈点击区域
    clonecircleMarker_item.push(L.circleMarker(latlngs[i], {
      color: '#eff24e',
      fillColor: '#eff24e',
      radius: i === 0 ? 1 : 6,
      fillOpacity: i === 0 ? 1 : 6,
      weight: i === 0 ? 1 : 6,
      opacity: 0
    }).addTo(state.map))
  }
  for (var item of latlngs) {
    //路线圆圈展示
    circleMarker_item.push(L.circle(item, {
      color: '#f24eed',
      fillColor: '#f24eed',
      radius: 1,
      fillOpacity: 1,
      weight: 1,
    }).addTo(state.map))
  }
  // 圆圈点击展示弹窗经纬度
  for (var item of clonecircleMarker_item) {
    item.on('click', (val) => {
      // console.log(val, 'val')
      handleMapMarerClick(This, val, '卡车路线')
    })
  }
  if (popup_ComAll.length) {
    for (var item of popup_ComAll) {
      state.map.removeLayer(item)
    }
    popup_ComAll = []
  }
  deleteAllPopup(This, popup_ComAll)
  popup_ComAll.push(allHandleMapMarerClick(This, comData, { autoClose: false, closeOnClick: false }))
 
  
}
// 绘制全部卡车路线
export async function drawgetTruckAll(This) {
  const { state } = This;
  const common = state.common;
  deleteTruck(state)
  var myIcon = L.icon({
    iconUrl: require('/src/assets/alltruck.png'),
    iconSize: [25, 25],
    iconAnchor: [10, 15],
    popupAnchor: [-3, -76],
  });
  var myIconUpdate = L.icon({
    iconUrl: require('/src/assets/truck.png'),
    iconSize: [25, 25],
    iconAnchor: [10, 15],
    popupAnchor: [-3, -76],
  });
  var endIcon = L.divIcon({
    html: '终点',
    className: styles.myDivIcon,
    iconSize: 30
  })
  if (common === null && !common.length) return
  for (var i = 0; i < common.length; i++) {
    var item = common[i].firstLatLonList
    if (item instanceof Array && item.length) {
      polyline_startmarkerAll.push(
        L.marker(item[0], { icon: myIcon, title: '卡车路线' }).addTo(state.map)
      )
    }
  }
  polyline_startmarkerAll.forEach(item => {
    item.on('click', (val) => {
      
      // 存在就删除图层
      if (polyline_groupAll) {
        state.map.removeLayer(polyline_groupAll);
      }
      if (polyline_startmarkerAllUpdate) {
        state.map.removeLayer(polyline_startmarkerAllUpdate);
      }
      // 存在就删除图层
      if (polyline_endmarkerAll) {
        state.map.removeLayer(polyline_endmarkerAll)
      }
      if (circleMarker_itemAll.length) {
        for (var item of circleMarker_itemAll) {
          state.map.removeLayer(item)
        }
        circleMarker_itemAll = []
      }
      if (clonecircleMarker_itemAll.length) {
        for (var item of clonecircleMarker_itemAll) {
          state.map.removeLayer(item)
        }
        clonecircleMarker_itemAll = []
      }
      // console.log(val, 'aaaaaaaaaa')
      // deleteAllPopup(This, popup_GantryAll)
      let filteItem = common.filter(it => {
        var latlngs = it.firstLatLonList
        if (latlngs instanceof Array && latlngs.length) {
          var truFirst = latlngs[0]
          if (truFirst[0] === val.latlng.lat && truFirst[1] === val.latlng.lng) {
            return it
          }
        }
      })
      if (filteItem.length) {
        var latlngs = filteItem[0].firstLatLonList
        polyline_startmarkerAllUpdate = L.marker(latlngs[0], { icon: myIconUpdate, title: '卡车路线' }).addTo(state.map)
        polyline_groupAll = L.polyline(latlngs, { color: 'blue', weight: 2 }).addTo(state.map);
        polyline_endmarkerAll = L.marker(latlngs[latlngs.length - 1], { icon: endIcon, title: '卡车路线' }).addTo(state.map);
        for (var i = 0; i < latlngs.length; i++) {
          // 路线圆圈点击区域
          clonecircleMarker_itemAll.push(L.circleMarker(latlngs[i], {
            color: '#eff24e',
            fillColor: '#eff24e',
            radius: i === 0 ? 1 : 6,
            fillOpacity: i === 0 ? 1 : 6,
            weight: i === 0 ? 1 : 6,
            opacity: 0
          }).addTo(state.map))
        }
        for (var item of latlngs) {
          //路线圆圈展示
          circleMarker_itemAll.push(L.circle(item, {
            color: '#f24eed',
            fillColor: '#f24eed',
            radius: 1,
            fillOpacity: 1,
            weight: 1,
          }).addTo(state.map))
        }
        // 圆圈点击展示弹窗经纬度
        for (var item of clonecircleMarker_itemAll) {
          item.on('click', (val) => {
            // console.log(val, 'val')
            handleMapMarerClick(This, val, '卡车路线')
          })
        }
      }

      This.comClick(filteItem)
      // const concatItem = filteItem.reduce(function (a, b) { return a.concat(b) })
      // popup_GantryAll.push(allHandleMapMarerClick(This, concatItem[0], { closeOnClick: false }))
      // This.longmenClick(concatItem)
    })
  })
  if (popup_ComAll.length) {
    for (var item of popup_ComAll) {
      state.map.removeLayer(item)
    }
    popup_ComAll = []
  }
  deleteAllPopup(This, popup_ComAll)
  for (var i = 0; i < common.length; i++) {
    if (common[i].action) {
      popup_ComAll.push(allHandleMapMarerClick(This, common[i], { autoClose: false, closeOnClick: false }))
    }
  }
}
// 绘制单个龙门吊
export async function drawGantryCrane(This) {
  const { state } = This;
  const longmenData = state.longmenData.length ? state.longmenData[0] : {};
  // console.log(longmenData, 'longmenDatalongmenData')
  if (circle_GantryCrane) {
    state.map.removeLayer(circle_GantryCrane)
  }
  if (circle_GantryCraneAll.length) {
    for (var item of circle_GantryCraneAll) {
      state.map.removeLayer(item)
    }
    circle_GantryCraneAll = []
  }
  deleteAllPopup(This, popup_GantryAll)
  if (!longmenData.fence) return;
  const latlngs = longmenData.fence.center;
  var myIcon = L.icon({
    iconUrl: require('/src/assets/lmd.png'),
    iconSize: [30, 30],
  });
  circle_GantryCrane = L.marker(latlngs, { icon: myIcon, title: '龙门吊' }).addTo(state.map)
  popup_GantryAll.push(allHandleMapMarerClick(This, longmenData, { autoClose: false, closeOnClick: false }))
  // circle_GantryCrane = L.circleMarker(latlngs, {
  //   color: '#ff5e00',
  //   fillColor: '#ff5e00',
  //   radius: 6,
  //   fillOpacity: 6,
  //   weight: 6,
  // }).addTo(state.map)
  circle_GantryCrane.on('click', (val) => {
    deleteAllPopup(This, popup_GantryAll)
    // console.log(val, 'val')
    popup_GantryAll.push(allHandleMapMarerClick(This, longmenData, { autoClose: false, closeOnClick: false }))
    // handleMapMarerClick(This, val, '龙门吊')
    // This.longmenClick([longmenData])
  })
  // const latlngs = longmenData.fence;
}
// 绘制全部龙门吊
export async function drawGantryCraneAll(This) {
  const { state } = This;
  const longmen = state.longmen;
  // console.log(longmen, 'longmenDatalongmenData')
  if (circle_GantryCrane) {
    state.map.removeLayer(circle_GantryCrane)
  }
  if (circle_GantryCraneAll.length) {
    for (var item of circle_GantryCraneAll) {
      state.map.removeLayer(item)
    }
    circle_GantryCraneAll = []
  }
  deleteAllPopup(This, popup_GantryAll)
  if (longmen.length) {
    var myIcon = L.icon({
      iconUrl: require('/src/assets/lmd.png'),
      iconSize: [30, 30],
      className: styles.IconRout
    });
    for (var i = 0; i < longmen.length; i++) {
      var item = longmen[i]
      if (item instanceof Array && item.length) {
        // item.forEach(it => {
        //   if (it.fence) {
        //     circle_GantryCraneAll.push(
        //       L.marker(it.fence.center, { icon: myIcon, title: '龙门吊' }).addTo(state.map)
        //     )
        //   }
        // })
        if (item[0].fence) {
          circle_GantryCraneAll.push(
            L.marker(item[0].fence.center, { icon: myIcon, title: '龙门吊' }).addTo(state.map)
          )
        }
        if (circle_GantryCraneAll.length) {
          // 同一组只展示第一个
          var items = item[0]
          if (items.fence) {
            let markerIcon1 = L.divIcon({
              html: `<span style="color:#FFFF00">${items.gantryID}</span>`,
              className: 'my-div-iconlmd',
              iconAnchor: [12, 27],
            });
            popup_GantryAll.push(L.marker(items.fence.center, { icon: markerIcon1, color:'#FFFF00' }).addTo(state.map))
            // popup_GantryAll.push(allHandleMapMarerClick(This, items, { autoClose: false, closeOnClick: false }))
          }
        }
      }

    }
    circle_GantryCraneAll.forEach((item, key) => {
      item.on('click', (val) => {
        deleteAllPopup(This, popup_GantryAll)
        let filteItem = longmen.filter(it => {
          if (it instanceof Array && it.length) {
            for (var m = 0; m < it.length; m++) {
              if (it[m].fence && it[m].fence.center[0] === val.latlng.lat && it[m].fence.center[1] === val.latlng.lng) {
                return it[m]
              }
            }
          }
        })
        const concatItem = filteItem.reduce(function (a, b) { return a.concat(b) })
        // handleMapMarerClick(This, val, '龙门吊')
        popup_GantryAll.push(allHandleMapMarerClick(This, concatItem[0], { closeOnClick: false }))
        This.longmenClick(concatItem)
      })
    })
  }
}
// 绘制单个桥吊
export async function drawTravellingBridge(This) {
  const { state } = This;
  const tBridgeData = state.tBridgeData.length ? state.tBridgeData[0] : {};
  // console.log(tBridgeData, 'tBridgeDatatBridgeData')
  if (circle_TravellingBridge) {
    state.map.removeLayer(circle_TravellingBridge)
  }
  if (circle_TravellingBridgeAll.length) {
    for (var item of circle_TravellingBridgeAll) {
      state.map.removeLayer(item)
    }
    circle_TravellingBridgeAll = []
  }
  deleteAllPopup(This, popup_TraveAll)
  if (!tBridgeData.fence) return;
  const latlngs = tBridgeData.fence.center;
  var myIcon = L.icon({
    iconUrl: require('/src/assets/qd.png'),
    iconSize: [30, 30],
  });
  circle_TravellingBridge = L.marker(latlngs, { icon: myIcon, title: '桥吊' }).addTo(state.map)
  popup_TraveAll.push(allHandleMapMarerClick(This, tBridgeData, { autoClose: false, closeOnClick: false }))
  // L.circleMarker(latlngs, {
  //   color: 'yellow',
  //   fillColor: 'yellow',
  //   radius: 6,
  //   fillOpacity: 6,
  //   weight: 6,
  // }).addTo(state.map)
  circle_TravellingBridge.on('click', (val) => {
    deleteAllPopup(This, popup_TraveAll)
    // console.log(val, 'val')
    popup_TraveAll.push(allHandleMapMarerClick(This, tBridgeData, { autoClose: false, closeOnClick: false }))
    // handleMapMarerClick(This, val, '桥吊')
  })
}
// 绘制全部桥吊
export async function drawTravellingBridgeAll(This) {
  const { state } = This;
  const tBridge = state.tBridge;
  // 防止地图每次点击重复渲染，先清除
  if (circle_TravellingBridge) {
    state.map.removeLayer(circle_TravellingBridge)
  }
  if (circle_TravellingBridgeAll.length) {
    for (var item of circle_TravellingBridgeAll) {
      state.map.removeLayer(item)
    }
    circle_TravellingBridgeAll = []
  }
  deleteAllPopup(This, popup_TraveAll)
  if (tBridge.length) {
    var myIcon = L.icon({
      iconUrl: require('/src/assets/qd.png'),
      iconSize: [30, 30],
    });
    for (var i = 0; i < tBridge.length; i++) {
      var item = tBridge[i]
      if (item instanceof Array && item.length) {
        item.forEach(it => {
          if (it.fence) {
            circle_TravellingBridgeAll.push(
              L.marker(it.fence.center, { icon: myIcon, title: '桥吊' }).addTo(state.map)
              // L.circleMarker(it.fence.center, {
              //   color: 'yellow',
              //   fillColor: 'yellow',
              //   radius: 6,
              //   fillOpacity: 6,
              //   weight: 6,
              // }).addTo(state.map)
            )
          }
        })
        if (circle_TravellingBridgeAll.length) {
          // 同一组只展示第一个
          var items = item[0]
          if (items.fence) {
            popup_TraveAll.push(allHandleMapMarerClick(This, items, { autoClose: false, closeOnClick: false }))
          }
        }
      }

    }
    // 地图桥吊点击事件
    circle_TravellingBridgeAll.forEach((item, key) => {
      item.on('click', (val) => {
        deleteAllPopup(This, popup_TraveAll)
        let filteItem = tBridge.filter(it => {
          if (it instanceof Array && it.length) {
            for (var m = 0; m < it.length; m++) {
              if (it[m].fence && it[m].fence.center[0] === val.latlng.lat && it[m].fence.center[1] === val.latlng.lng) {
                return it[m]
              }
            }
          }
        })
        const concatItem = filteItem.reduce(function (a, b) { return a.concat(b) })
        // allHandleMapMarerClick(This, concatItem[0], {})
        popup_TraveAll.push(allHandleMapMarerClick(This, concatItem[0], { closeOnClick: false }))
        This.bridgeClick(concatItem)
      })
    })
  }

}
// 清空弹窗
function deleteAllPopup(This, list) {
  if (list.length) {
    for (var item of list) {
      This.state.map.removeLayer(item)
    }
    list = []
  }
}
// 单击显示弹窗 （显示经纬度）
function handleMapMarerClick(This, item, title) {
  let content = `<div class="boundaryMask-popup">`
    + `<p>${title}</p>`
    + `<div style="height:20px" id="pptnMapChart">纬度：${item.latlng.lat}</div>`
    + `<div style="height:20px" id="pptnMapCharts">经度：${item.latlng.lng}</div>`
    + ` </div>`;
  L.popup()
    .setLatLng([item.latlng.lat, item.latlng.lng])
    .setContent(content)
    .openOn(This.state.map);
}
// 全部弹窗展示  不支持点击空白关闭弹窗 （龙门吊，桥吊使用，只展示名字）
function allHandleMapMarerClick(This, items, data) {
  var color = items.craneId?'black':items.gantryID?'yellow':'blue'
  var list = []
  if (items.currRouteNo==1) {
    items.firstLatLonList?list = items.firstLatLonList[0]:list = [0,0]
  } else {
    items.secondLatLonList?list = items.secondLatLonList[0]:list = [0,0]
  }
  return L.popup({ ...data, maxHeight: '20px', maxWidth: '20px' })
    .setLatLng(items.fence?items.fence.center:list)
    .setContent(`<div class="boundaryMasks" style="color:${color}">${items.craneId || items.gantryID || items.truckId}</div>`)
    .openOn(This.state.map)
}
// 卡车清空图层函数
function deleteTruck(state) {
  // 存在就删除图层
  if (polyline_group) {
    state.map.removeLayer(polyline_group);
  }
  // 存在就删除图层
  if (polyline_startmarker) {
    state.map.removeLayer(polyline_startmarker)
  }
  // 存在就删除图层
  if (polyline_endmarker) {
    state.map.removeLayer(polyline_endmarker)
  }
  // 存在就删除图层  全部路线
  if (polyline_groupAll) {
    state.map.removeLayer(polyline_groupAll);
  }
  // 存在就删除图层 全部终点
  if (polyline_endmarkerAll) {
    state.map.removeLayer(polyline_endmarkerAll)
  }
  if (polyline_startmarkerAllUpdate) {
    state.map.removeLayer(polyline_startmarkerAllUpdate)
  }
  // 清空全部车头
  if (polyline_startmarkerAll.length) {
    for (var item of polyline_startmarkerAll) {
      state.map.removeLayer(item)
    }
    polyline_startmarkerAll = []
  }
  // 清空坐标圆
  if (circleMarker_item.length) {
    for (var item of circleMarker_item) {
      state.map.removeLayer(item)
    }
    circleMarker_item = []
  }
  if (clonecircleMarker_item.length) {
    for (var item of clonecircleMarker_item) {
      state.map.removeLayer(item)
    }
    clonecircleMarker_item = []
  }
  if (circleMarker_itemAll.length) {
    for (var item of circleMarker_itemAll) {
      state.map.removeLayer(item)
    }
    circleMarker_itemAll = []
  }
  if (clonecircleMarker_itemAll.length) {
    for (var item of clonecircleMarker_itemAll) {
      state.map.removeLayer(item)
    }
    clonecircleMarker_itemAll = []
  }
}
function points(p1,p2) {
  var a = p2[0]-p1[0];
  var b = p2[1]-p1[1];
  return Math.sqrt(a*a+b*b);
}
//单个集卡运行
export async function jkCoordinate(This,arr,time,bs) {
  for(var i = 0; i < 1000; i++) {
    clearTimeout(timer1[i]);
  }
  jksp = true
  deleteAllPopup(This, jk)
  deleteAllPopup(This, popup_TraveAlls)
  const { state } = This;
  var myIcon = L.icon({
    iconUrl: require('/src/assets/truck.png'),
    iconSize: [20, 20],
    iconAnchor: [10, 15],
    popupAnchor: [-3, -76],
  });
  bs?bs=Number(bs):bs=1;
  var a = L.marker(arr[0], { icon: myIcon, title: '卡车路线' }).addTo(state.map)
  for(var i=0; i<arr.length; i++){
    (function(n){
      timer1[i] = setTimeout(function(){
          if(jksp){
            state.map.removeLayer(a)
            a = L.marker(arr[n], { icon: myIcon, title: '卡车路线' }).addTo(state.map)
            jk.push(a)
          }
        }, (time/arr.length)*1000*n/bs)
      })(i)
    }
}
//单个集卡切片
export async function jkSection(This,arr,time) {
  for(var i = 0; i < 1000; i++) {
    clearTimeout(timer1[i]);
  }
  deleteAllPopup(This, jk)
  deleteAllPopup(This, popup_TraveAlls)
  const { state } = This;
  var myIcon = L.icon({
    iconUrl: require('/src/assets/truck.png'),
    iconSize: [20, 20],
    iconAnchor: [10, 15],
    popupAnchor: [-3, -76],
  });
  var a = L.marker(arr[arr.length-1], { icon: myIcon, title: '卡车路线' }).addTo(state.map)
  jk.push(a)
}
export async function jkStop() {
  jksp = false
}
//全部集卡运行
export async function jkAllCoordinate(This,arr,nameArr,time,bs) {
  jksp = true
  deleteAllPopup(This, polyline_startmarkerAll)
  deleteAllPopup(This, popup_ComAll)
  deleteAllPopup(This, jk)
  deleteAllPopup(This, popup_TraveAlls)
  const { state } = This;
  var myIcon = L.icon({
    iconUrl: require('/src/assets/truck.png'),
    iconSize: [20, 20],
    iconAnchor: [10, 15],
    popupAnchor: [-3, -76],
  });
  var newArr = arr.filter(item => item.length>0) 
  var newArrName = nameArr.filter(item => item.length>0) 
  var tArr = JSON.parse(JSON.stringify(newArr))
  bs?bs=Number(bs):bs=1;
  
  for (var i = 0; i < tArr.length; i++) {
    for (var j = 0; j < tArr[i].length; j++) {
      tArr[i][j] = {
        fence: {
          center: tArr[i][j]
        },
        truckId: newArrName[i]
      }
    }
  }
  var a = []
  var b = []
  for(let j=0; j<newArr.length; j++){
    let markerIcon1 = L.divIcon({
      html: tArr[j][0].truckId,
      className: 'my-div-icon',
      iconAnchor: [12, 27],
    });
    a[j] = L.marker(newArr[j][0], { icon: myIcon, title: '卡车路线' }).addTo(state.map)
    b[j] = L.marker(newArr[j][0], { icon: markerIcon1 }).addTo(state.map);
    for(let i=0; i<newArr[j].length; i++){
      (function(n){
        setTimeout(function(){
          if(jksp){
            state.map.removeLayer(a[j])
            state.map.removeLayer(b[j])
            a[j] = L.marker(newArr[j][n], { icon: myIcon, title: '卡车路线' }).addTo(state.map)
            let markerIcon = L.divIcon({
              html: tArr[j][n].truckId,
              className: 'my-div-icon',
              iconAnchor: [12, 27],
            });
            b[j] = L.marker(newArr[j][n], { icon: markerIcon }).addTo(state.map);
            popup_TraveAlls.push(b[j])
            jk.push(a[j])
          }
        }, (time/newArr[j].length)*1000*n/bs)
      })(i)
    }
  }
}
//全部集卡切片
export async function jkAllSection(This,arr,nameArr,time) {
  jksp = false
  deleteAllPopup(This, polyline_startmarkerAll)
  deleteAllPopup(This, popup_ComAll)
  deleteAllPopup(This, jk)
  deleteAllPopup(This, popup_TraveAlls)
  const { state } = This;
  var myIcon = L.icon({
    iconUrl: require('/src/assets/truck.png'),
    iconSize: [20, 20],
    iconAnchor: [10, 15],
    popupAnchor: [-3, -76],
  });
  var newArr = arr.filter(item => item.length>0) 
  var newArrName = nameArr.filter(item => item.length>0) 
  var tArr = JSON.parse(JSON.stringify(newArr))
  for (var i = 0; i < tArr.length; i++) {
    for (var j = 0; j < tArr[i].length; j++) {
      tArr[i][j] = {
        fence: {
          center: tArr[i][j]
        },
        truckId: newArrName[i]
      }
    }
  }
  var a = []
  var b = []
  for(let j=0; j<newArr.length; j++){
    let markerIcon1 = L.divIcon({
      html: tArr[j][0].truckId,
      className: 'my-div-icon',
      iconAnchor: [12, 27],
    });
    a[j] = L.marker(newArr[j][newArr[j].length-1], { icon: myIcon, title: '卡车路线' }).addTo(state.map)
    b[j] = L.marker(newArr[j][newArr[j].length-1], { icon: markerIcon1 }).addTo(state.map);
    popup_TraveAlls.push(b[j])
    jk.push(a[j])
  }
}

// 龙门吊切片
export async function lmdPlanPath(This,time){
  for(var i = 0; i < 10000; i++) {
    clearTimeout(timer3[i]);
  }
  const { state } = This;
  const longmend = state.longmen;
  var longmen = JSON.parse(JSON.stringify(longmend))
  if (longmen[0].ty) {
    longmen.shift()
  }
  var nTime = new Date(time).getTime()
  deleteAllPopup(This, popup_GantryAll)
  if (circle_GantryCrane) {
    state.map.removeLayer(circle_GantryCrane)
  }
  if (circle_GantryCraneAll.length) {
    for (var item of circle_GantryCraneAll) {
      state.map.removeLayer(item)
    }
    circle_GantryCraneAll = []
  }
  var arr = []
  for (let i = 0; i < longmen.length; i++) {
    arr.push(getTimeObj(longmen[i],nTime))
  }
  var myIcon = L.icon({
    iconUrl: require('/src/assets/lmd.png'),
    iconSize: [30, 30],
    className: styles.IconRout
  });
  for (var i = 0; i < arr.length; i++) {
    var item = longmen[i]
    // if (item instanceof Array && item.length) {
      // item.forEach(it => {
        if (arr[i].fence) {
          circle_GantryCraneAll.push(
            L.marker(arr[i].fence.center, { icon: myIcon, title: '龙门吊' }).addTo(state.map)
          )
        }
      // })
      if (circle_GantryCraneAll.length) {
        // 同一组只展示第一个
        var items = item[0]
        if (arr[i].fence) {
          let markerIcon1 = L.divIcon({
            html: `<span style="color:#FFFF00">${items.gantryID}</span>`,
            className: 'my-div-iconlmd',
            iconAnchor: [12, 27],
          });
          popup_GantryAll.push(L.marker(arr[i].fence.center, { icon: markerIcon1, color:'#FFFF00' }).addTo(state.map))
          // popup_GantryAll.push(allHandleMapMarerClick(This, arr[i], { autoClose: false, closeOnClick: false }))
        }
      }
    // }

  }
}
//龙门吊运行
export async function lmdPlanPathyx(This,time,s,bs){
  for(var i = 0; i < 10000; i++) {
    clearTimeout(timer3[i]);
  }
  bs?bs=Number(bs):bs=1;
  lmdsp = true;
  const { state } = This;
  const longmend = state.longmen;
  var longmen = JSON.parse(JSON.stringify(longmend))
  if (longmen[0].ty) {
    longmen.shift()
  }
  var nTime = new Date(time).getTime()
  deleteAllPopup(This, popup_GantryAll)
  if (circle_GantryCrane) {
    state.map.removeLayer(circle_GantryCrane)
  }
  if (circle_GantryCraneAll.length) {
    for (var item of circle_GantryCraneAll) {
      state.map.removeLayer(item)
    }
    circle_GantryCraneAll = []
  }
  
  var myIcon = L.icon({
    iconUrl: require('/src/assets/lmd.png'),
    iconSize: [30, 30],
    className: styles.IconRout
  });
  for (let n = 0; n < s/bs; n++) {
    // console.log(1000*n,bs,999,s,lmdsp,nTime-(1000*(s-n)))
    timer3[n] = setTimeout(()=>{
      if(lmdsp){
        deleteAllPopup(This, popup_GantryAll)
        if (circle_GantryCrane) {
          state.map.removeLayer(circle_GantryCrane)
        }
        if (circle_GantryCraneAll.length) {
          for (var item of circle_GantryCraneAll) {
            state.map.removeLayer(item)
          }
          circle_GantryCraneAll = []
        }
        var arr = []
        for (let i = 0; i < longmen.length; i++) {
          arr.push(getTimeObj(longmen[i],nTime-(1000*(s-n*bs))))
        }
        for (var i = 0; i < arr.length; i++) {
          var item = longmen[i]
          if (arr[i].fence) {
            circle_GantryCraneAll.push(
              L.marker(arr[i].fence.center, { icon: myIcon, title: '龙门吊' }).addTo(state.map)
            )
          }
          // console.log(arr[i],111)
          if (circle_GantryCraneAll.length) {
          //   var items = item[0]
            if (arr[i].fence) {
              let markerIcon1 = L.divIcon({
                // html: arr[i].gantryID,
                html: `<span style="color:#FFFF00">${arr[i].gantryID}</span>`,
                className: 'my-div-iconlmd',
                iconAnchor: [12, 27],
              });
              popup_GantryAll.push(L.marker(arr[i].fence.center, { icon: markerIcon1, color:'#FFFF00' }).addTo(state.map))
          //     popup_GantryAll.push(allHandleMapMarerClick(This, arr[i], { autoClose: false, closeOnClick: false }))
            }
          }
        }
      }
    },1000*n)
  }
}
export async function lmdzt(){
  lmdsp = false
}


//时间格式 dateFormat("YYYY-mm-dd HH:MM:SS", 1637828100000)
export function dateFormat(fmt, date) {
  date = new Date(date)
  let ret;
  const opt = {
      "Y+": date.getFullYear().toString(),        // 年
      "m+": (date.getMonth() + 1).toString(),     // 月
      "d+": date.getDate().toString(),            // 日
      "H+": date.getHours().toString(),           // 时
      "M+": date.getMinutes().toString(),         // 分
      "S+": date.getSeconds().toString()          // 秒
  };
  for (let k in opt) {
      ret = new RegExp("(" + k + ")").exec(fmt);
      if (ret) {
          fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
      };
  };
  return fmt;
}

function getTimeObj(list, time) {
  let obj = {};
  list.some((item, index) => {
      var stime = new Date(item.predictStartTime).getTime()
      var etime = new Date(item.predictEndTime).getTime()
      // var ltime = new Date(list[list.length-1].predictEndTime).getTime()
      // var nexttime = list[index+1]? new Date(list[index+1].predictStartTime).getTime():0
      var prevtime = list[index-1]? new Date(list[index-1].predictEndTime).getTime():0
      if (time < stime && index === 0) {
          obj = item;
          return;
      } else if (index && time < stime && time > prevtime) {
          obj = list[index - 1];
          return;
      } else if (stime <= time && time <= etime) {
          obj = item;
          return;
      } else if (list.length - 1 === index && time > etime) {
          obj = item;
          return;
      }
  });
  return obj;
}